import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/views/module_case/case_create/logic.dart';

import '../../../constants.dart';
import '../../../models/case_list_entity.dart';
import '../../../remote/exception.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class SealCreateLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  final sealPaperType = Rxn<SealPaperType>();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController printNumController = TextEditingController();
  final TextEditingController remarkController = TextEditingController();

  var sealType = 0.obs;
  var attachmentNames = [].obs;
  final List<PlatformFile> _paths = [];

  var caseId = ''.obs;
  var caseName = ''.obs;

  var caseList = <CaseInfo>[].obs;
  var selectedCase = Rxn<CaseInfo>();

  @override
  void onInit() {
    super.onInit();
    SealCreateParams params = Get.arguments;

    sealPaperType.value = params.sealPaperType;
    if (sealPaperType.value!.value <= 10) {
      _getCaseList();
    }
  }

  // 选择印章类型
  void setSelectedSealType(int type) {
    sealType.value = type;
  }

  // 选中案件
  void onSelectCase(CaseInfo caseInfo) {
    selectedCase.value = caseInfo;
    caseId.value = caseInfo.id!;
  }

  void onCreateCase() {
    Get.back();
    Get.toNamed(RouteGet.caseCreate, arguments: CaseCreatePageType.seal)
        ?.then((value) {
      if (value != null) {
        // 将value添加到caseList的第一个位置
        caseList.insert(0, value);

        selectedCase.value = value;
        caseId.value = value.id!;
      }
    });
  }

  // 选择文件
  void pickFile() async {
    var files = (await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    ))
        ?.files;

    if (files != null && files.isNotEmpty) {
      _paths.addAll(files);
      attachmentNames.addAll(files.map((e) => e.name).toList());
    }
  }

  // 删除文件
  void deleteFile(int index) {
    _paths.removeAt(index);
    attachmentNames.removeAt(index);
  }

  void onSubmit() {
    if (formKey.currentState!.validate()) {
      EasyLoading.show(status: '提交申请中...', dismissOnTap: true);

      _createSeal();
    }
  }

  void _getCaseList() {
    apiService.listAllCase(commonService.getRole()).then((caseList) {
      if (caseList != null) {
        this.caseList.addAll(caseList.all!);
      }
    });
  }

  bool _onNetworkError(ApiException e) {
    EasyLoading.showError(e.toString());
    return true;
  }

  void _createSeal() {
    var printNum = int.parse(printNumController.text);
    var remark = remarkController.text;

    apiService
        .createSeal(
            sealPaperType: sealPaperType.value!.value,
            sealType: sealType.value,
            printNum: printNum,
            caseId: caseId.value,
            remark: remark,
            onError: _onNetworkError)
        .then((value) {
      if (value != null) {
        _uploadFile(value.value['data']['id']);
        Get.back(result: true);
        EasyLoading.dismiss();
        Get.snackbar('提示', '创建成功');
      } else {
        EasyLoading.showError('申请失败，请稍后重试!');
      }
    });
  }

  void _uploadFile(String caseId) {
    if (_paths.isEmpty) {
      return;
    }

    for (var path in _paths) {
      apiService
          .fileUpload(
        action: 'upload-apply-file',
        fileIndex: 0,
        filePath: path.path!,
        caseId: caseId,
        onError: _onNetworkError,
      )
          .then((value) {
        if (value == null) {
          EasyLoading.showError('附件上传失败');
          return;
        } else {
          EasyLoading.dismiss();
        }
      });
    }
  }
}

class SealCreateParams {
  final SealPaperType sealPaperType;
  final String? caseId;
  final String? caseName;

  SealCreateParams({required this.sealPaperType, this.caseId, this.caseName});
}
